package casbinPolicy

import (
	"context"
	"gf_blog_admin/internal/dao"

	"github.com/casbin/casbin/v2"
)

var Enforcer *casbin.Enforcer

// InitEnforcer 初始化
func InitEnforcer(ctx context.Context) error {
	var (
		table     = dao.BlRules.Table()
		modelPath = "manifest/config/casbin/rbac-model.conf"
	)
	a, err := NewAdapter(table)
	if err != nil {
		return err
	}
	Enforcer, err = casbin.NewEnforcer(modelPath, a)
	if err != nil {
		return err
	}
	loadPermissions(ctx)
	return nil
}

func loadPermissions(ctx context.Context) {
	return
}

func Clear(ctx context.Context) (err error) {
	policy, _ := Enforcer.GetPolicy()
	_, err = Enforcer.RemovePolicies(policy)
	if err != nil {
		return
	}
	// 检查是否清理干净
	if len(policy) > 0 {
		return Clear(ctx)
	}
	return
}

func Refresh(ctx context.Context) (err error) {
	if err = Clear(ctx); err != nil {
		return err
	}
	loadPermissions(ctx)
	return
}
